import asyncio
import websockets

connected_clients = set()


async def handle_client(websocket, path):
    connected_clients.add(websocket)
    try:
        async for message in websocket:
            # 广播消息给所有客户端
            for client in connected_clients:
                await client.send(message)
    except Exception:
        pass
    finally:
        # 客户端断开连接时移除
        connected_clients.remove(websocket)


start_server = websockets.serve(handle_client, "localhost", 8899)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
